package com.sixstones.fragment.web.fragment;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sixstones.fragment.entity.CatagoryEntity;
import com.sixstones.fragment.enums.ResultEnum;
import com.sixstones.fragment.service.CatagoryService;
import com.sixstones.fragment.vo.CatagoryInfo;
import com.sixstones.fragment.vo.FragmentResult;

@Controller
@RequestMapping(value = "/catagory")
public class CatagoryController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private CatagoryService service;

	@RequestMapping(value = "/toAdd")
	public String toAdd() {
		logger.info("to add fragment catagory");
		return "fragment.catagory.add";
	}

	@RequestMapping(value = "/add", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public FragmentResult add(String name, String desc) {
		logger.info("to add fragment catagory,name = {},desc = {}", name, desc);
		FragmentResult result = new FragmentResult(ResultEnum.FAIL, false);
		try {
			int count = service.addCatagory(name, desc);
			if (count == 0) {
				result.setResult(ResultEnum.CATAGORY_ADDERROR, false);
			}
			result.setResult(ResultEnum.SUCCESS, true);
		} catch (Exception e) {
			result.setCode(ResultEnum.FAIL.getCode());
			result.setError(e.getMessage());
			result.setSuccess(false);
		}
		return result;
	}

	@RequestMapping(value = "/")
	public String catagoryIndex(Model model) {
		List<CatagoryEntity> all = service.queryAll();
		model.addAttribute("catagories", all);
		return "fragment.catagory.index";
	}

	@RequestMapping(value = "/{id}")
	public String catagoryPage(@PathVariable("id") int catagoryId, Model model) {
		CatagoryInfo info = service.getCatagoryInfo(catagoryId,true);
		model.addAttribute("info", info);
		return "fragment.catagory.info";
	}
}
